package org.sixtythousand.joker.http;

import org.sixtythousand.joker.AbstractConnection;
import org.sixtythousand.joker.Request;
import org.sixtythousand.joker.handler.Handler;
import org.sixtythousand.joker.handler.HandlerManager;
import org.sixtythousand.joker.handler.LinkedHandler;
import org.sixtythousand.joker.util.Callback;

/**
 * @author zhoulk
 * @date 2023/10/13 13:36
 * @desc
 */
public class HttpConnection extends AbstractConnection {

    protected Handler handler;

    protected HttpConnection(HttpChannel channel, Handler handler) {
        super(channel);
        this.handler = handler;
        channelCallback = newChannelCallback();
    }

    @Override
    public void doRead(Object msg) {
        if (msg instanceof Request) {
            Request request = (Request) msg;
//            if (request.isStarted()) {
                handler.handle(newHttpRequest(request), newHttpResponse(request));
//            }
        }
    }

    protected HttpRequest newHttpRequest(Request request) {
        if (request instanceof HttpRequest) {
            return (HttpRequest) request;
        } else {
            // todo
            return null;
        }
    }

    protected HttpResponse newHttpResponse(Request request) {
        return null;
    }

    @Override
    public Callback newChannelCallback() {
        return new ReadCallBack();
    }


    class ReadCallBack implements Callback {
        @Override
        public Runnable asyncSucceeded(Object request) {
            return () -> {
                System.out.println("run");
                doRead(request);
            };
        }
    }
}
